package com.quanxiaoha.weblog.web.controller;

import com.quanxiaoha.weblog.common.aspect.ApiOperationLog;
import com.quanxiaoha.weblog.common.enums.ResponseCodeEnum;
import com.quanxiaoha.weblog.common.exception.BizException;
import com.quanxiaoha.weblog.common.utils.JsonUtil;
import com.quanxiaoha.weblog.common.utils.Response;
import com.quanxiaoha.weblog.web.model.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

@RestController
@Slf4j
@Api(tags = "首页模块")
public class TestController {

    @PostMapping("/test")
    @ApiOperationLog(description = "请求日志切面测试接口")
    @ApiOperation(value = "请求日志切面测试接口")
    public Response<String> test(@RequestBody @Validated User user) {
//        // 是否存在校验错误
//        if (!bindingResult.hasErrors()) {
//            return Response.success();
//        }
//        // 获取校验不通过字段的提示信息
//        String errorMsg = bindingResult.getFieldErrors()
//                .stream()
//                .map(FieldError::getDefaultMessage)
//                .collect(Collectors.joining(", "));
        return Response.success();
    }

    @PostMapping("/exception")
    @ApiOperationLog(description = "异常处理测试接口")
    @ApiOperation(value = "异常处理测试接口")
    public Response<String> exception() {
        // 手动抛异常，入参是前面定义好的异常码枚举，返参统一交给全局异常处理器搞定
        throw new BizException(ResponseCodeEnum.PRODUCT_NOT_FOUND);
    }

    @PostMapping("/allException")
    @ApiOperationLog(description = "其它异常处理测试接口")
    @ApiOperation(value = "其它异常处理测试接口")
    public Response<String> allException() {
        // 主动定义一个运行时异常，分母不能为零
        int i = 1 / 0;
        return Response.success();
    }

    @PostMapping("/jackson")
    @ApiOperationLog(description = "测试jackson序列化与反序列化")
    @ApiOperation(value = "测试jackson序列化与反序列化")
    public Response<User> jackson(@RequestBody @Validated User user) {
        log.info(JsonUtil.toJsonString(user));
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateDate(LocalDate.now());
        user.setTime(LocalTime.now());
        return Response.success(user);
    }

    @GetMapping("/admin/security")
    @ApiOperationLog(description = "测试SpringSecurity")
    @ApiOperation(value = "测试SpringSecurity")
    public Response<String> security() {
        return Response.success();
    }

    @GetMapping("/toLogin")
    @ApiOperationLog(description = "测试Security")
    @ApiOperation(value = "测试Security")
    public Response<String> toLogin() {
        return Response.success();
    }
}